package com.qf.test2;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qf.pojo.User;
import org.junit.Test;
import org.springframework.util.SerializationUtils;
import redis.clients.jedis.Jedis;

import java.io.IOException;

/**
 * 存储对象
 * @author zjw
 * @description
 * @date 2021/10/29 17:25
 */
public class DemoTest {


    /**
     * JSON字符串形式存储
     */
    @Test
    public void setByJSON() throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        User user = new User();
        String value = mapper.writeValueAsString(user);
        //1. 连接Redis，只提供了有参构造，没有set方法设置host和port的方式
        Jedis jedis = new Jedis("192.168.41.41",6379);

        //2. 操作,
        jedis.set("user",value);

        //3. 释放资源
        jedis.close();
    }

    /**
     * 获取Redis中的JSON字符串并反序列化
     * @throws IOException
     */
    @Test
    public void getByJSON() throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        //1. 连接Redis，只提供了有参构造，没有set方法设置host和port的方式
        Jedis jedis = new Jedis("192.168.41.41",6379);

        //2. 操作,
        String value = jedis.get("user");
        User user = mapper.readValue(value, User.class);
        System.out.println(user);

        //3. 释放资源
        jedis.close();
    }


    /**
     * 存储对象，以byte[]
     */
    @Test
    public void setByByteArray(){
        // 用谁序列化，后期获取数据就用谁反序列化……
        User user = new User();
        byte[] value = SerializationUtils.serialize(user);
        byte[] key = SerializationUtils.serialize("user");
        //1. 连接Redis，只提供了有参构造，没有set方法设置host和port的方式
        Jedis jedis = new Jedis("192.168.41.41",6379);

        jedis.set(key,value);

        //3. 释放资源
        jedis.close();
    }


    /**
     * 从Redis中获取byte[]数据
     */
    @Test
    public void getByByteArray(){
        //1.
        Jedis jedis = new Jedis("192.168.41.41",6379);

        //2.
        byte[] key = SerializationUtils.serialize("user");
        byte[] value = jedis.get(key);
        User user = (User) SerializationUtils.deserialize(value);
        System.out.println(user);

        //3.
        jedis.close();
    }
}
